package fr.generali.accueilclient.gwt.client.ui.components.popup;

import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Event.NativePreviewEvent;

import fr.generali.accueilclient.gwt.client.ui.components.form.button.ActionButton;
import fr.generali.accueilclient.gwt.client.ui.components.form.button.CancelButton;

/**
 * Boite de dialogue qui fixe les boutons à deux éléments : un {@link ActionButton} et un
 * {@link CancelButton}.
 * 
 * Cette classe réduit considérablement la quantité de code à écrire pour les popup
 * disposant généralement de deux boutons.
 * 
 * @author M. Abdennebi 13 avr. 2012
 * 
 */
public class ChoicePopupBox extends PopupBox {

	private final ActionButton actionButton;

	private final CancelButton cancelButton;

	private final Command defaultCommand = new Command() {
		@Override
		public void execute() {
			hide();
		}
	};

	public ChoicePopupBox() {
		this(ActionButton.DEFAULT_NAME, CancelButton.DEFAULT_NAME);
	}

	public ChoicePopupBox(String actionText, String cancelText) {
		cancelButton = getButtonBar().addCancelButton(cancelText);
		cancelButton.setCommand(defaultCommand);
		actionButton = getButtonBar().addActionButton(actionText);
		actionButton.setFocus(true);
	}

	public void setActionCommand(final Command command) {
		actionButton.setCommand(command);
	}

	public void setCancelCommand(final Command command) {
		cancelButton.setCommand(command);
	}

    public ActionButton getActionButton() {
        return actionButton;
    }

    public CancelButton getCancelButton() {
        return cancelButton;
    }
	
	@Override
	protected void onPreviewNativeEvent(NativePreviewEvent event) {
		super.onPreviewNativeEvent(event);
		switch (event.getTypeInt()) {
		case Event.ONKEYDOWN:
			if (event.getNativeEvent().getKeyCode() == KeyCodes.KEY_ENTER) {
				
				if (event.getSource() != null && event.getSource().equals(cancelButton)) {
					cancelButton.getCommand().execute();
				} else {
					actionButton.getCommand().execute();	
				}
			}
			break;
		}
	}

}
